<script setup>
import { Icon, Swipe, SwipeItem } from 'vant';
import { ref, watchEffect } from 'vue';

const props = defineProps({
    show: Boolean,
    videoList: Array,
    videoIndex: Number,
    clickVideo: Object,
    onClose: Function,
})
const show = ref(false)
const videoList = ref([])
const videoIndex = ref(0)

watchEffect(() => {
    show.value = props.show
    videoList.value = props.videoList

    if (props.videoList && props.clickVideo) {
        videoIndex.value = props.videoList.findIndex(it => it.name === props.clickVideo.name)
    } else {
        videoIndex.value = props.videoIndex
    }
})

const onSwipeChange = (index) => {
    requestAnimationFrame(() => {
        const videos = document.querySelectorAll('video');
        if (videos && videos.length > videoIndex.value) {
            const video = videos[videoIndex.value]
            if (video) {
                video.pause();  // 暂停前一个视频
            }
        }
        videoIndex.value = index
        if (videos && videos.length > videoIndex.value) {
            const video = videos[videoIndex.value]
            if (video) {
                video.play();   // 播放当前的视频
            }
        }
    })
}

</script>

<template>
    <div v-if="show" class="root-container">
        <Swipe @change="onSwipeChange" :loop="false" :initial-swipe="videoIndex" style="width: 100%; height: 100vh;"
            vertical>
            <SwipeItem v-for="(it, index) in videoList" :key="index">
                <div class="video-container" @click="() => onClose()">
                    <video :poster="`/api/get-video-cover?filename=${it.name}`" width="100%" height="auto" controls
                        preload loop muted autoplay>
                        <source :src="it.url">
                    </video>
                </div>
            </SwipeItem>
            <template #indicator="{ active, total }">
                <div class="custom-indicator">{{ active + 1 }}/{{ total }}</div>
            </template>
        </Swipe>

        <div class="close" @click="() => onClose()">
            <Icon name="cross" size="24px" color="#eeeeee99" />
        </div>
    </div>
</template>

<style lang="scss" scoped>
.root-container {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background: black;
    margin: 0 !important;
    padding: 0;
    z-index: 1000;
}

.video-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.close {
    position: fixed;
    top: 16px;
    right: 16px;
    border: #eeeeee99 solid 2px;
    border-radius: 100px;
    padding: 2px;
    z-index: 100;
}

.custom-indicator {
    position: fixed;
    right: 5px;
    bottom: 5px;
    padding: 2px 5px;
    font-size: 12px;
    background: rgba(0, 0, 0, 0.1);
}
</style>